//#include "stdafx.h"
#include "ThreadLock.h"

//-------------------CCritSecLock-----------------------------
//-------------------------------------------------------------
#if defined(FOREST_PLATFORM_WINDOWS)

CCritSecLock::CCritSecLock()
	: m_pCS(NULL)
{
	m_pCS = new CRITICAL_SECTION;
	if(m_pCS)
	{
		InitializeCriticalSection(m_pCS);
	}
};

CCritSecLock::~CCritSecLock()
{
	if(m_pCS)
	{
		delete m_pCS;
		m_pCS = NULL;
	}
}

void CCritSecLock::Lock() const
{
	if(m_pCS)
	{
		EnterCriticalSection(m_pCS);
	}
}

void CCritSecLock::Unlock() const
{
	if(m_pCS)
	{
		LeaveCriticalSection(m_pCS);
	}
}

#endif




//-------------------CMutexLock------------------------------
//-------------------------------------------------------------
CMutexLock::CMutexLock(BOOL bInitiallyOwn/* = FALSE*/)
{
#if defined(FOREST_PLATFORM_WINDOWS)
	m_Mutex = ::CreateMutex(NULL,bInitiallyOwn,NULL);

#elif defined(FOREST_PLATFORM_LINUX)
	pthread_mutex_init(&m_Mutex,NULL);
#endif
}




CMutexLock::~CMutexLock()
{
#if defined(FOREST_PLATFORM_WINDOWS)
	::CloseHandle(m_Mutex);

#elif defined(FOREST_PLATFORM_LINUX)
	pthread_mutex_destroy(&m_Mutex);
#endif
}


void CMutexLock::Lock() const
{
#if defined(FOREST_PLATFORM_WINDOWS)
	DWORD dw = WaitForSingleObject(m_Mutex,INFINITE);

#elif defined(FOREST_PLATFORM_LINUX)
	pthread_mutex_lock(&m_Mutex);
#endif
}


void CMutexLock::Unlock() const
{
#if defined(FOREST_PLATFORM_WINDOWS)
	::ReleaseMutex(m_Mutex);


#elif defined(FOREST_PLATFORM_LINUX)
	pthread_mutex_unlock(&m_Mutex);
#endif
}

//-------------------CEventLock------------------------------
//-------------------------------------------------------------
CEventLock::CEventLock(BOOL bInitiallyOwn/* = FALSE*/)
{
#if defined(FOREST_PLATFORM_WINDOWS)
	m_Event = ::CreateEvent(NULL,FALSE,bInitiallyOwn,NULL);

// #elif defined(FOREST_PLATFORM_LINUX)
// 	pthread_mutex_init(&m_Mutex,NULL);
#endif
}


CEventLock::~CEventLock()
{
#if defined(FOREST_PLATFORM_WINDOWS)
	::CloseHandle(m_Event);

// #elif defined(FOREST_PLATFORM_LINUX)
// 	pthread_mutex_destroy(&m_Mutex);
#endif
}


void CEventLock::Lock() const
{
#if defined(FOREST_PLATFORM_WINDOWS)
 	DWORD dw = WaitForSingleObject(m_Event,INFINITE);

// #elif defined(FOREST_PLATFORM_LINUX)
// 	pthread_mutex_lock(&m_Mutex);
#endif
}


void CEventLock::Unlock() const
{
#if defined(FOREST_PLATFORM_WINDOWS)
	SetEvent(m_Event);


// #elif defined(FOREST_PLATFORM_LINUX)
// 	pthread_mutex_unlock(&m_Mutex);
#endif
}


//-------------------CScopeLock--------------------------------
//-------------------------------------------------------------
CScopeLock::CScopeLock(const IThreadLock* pThreadMutex)
	: m_pThreadMutex(pThreadMutex)
{
	if(m_pThreadMutex)
	{
		m_pThreadMutex->Lock();
	}
}


CScopeLock::~CScopeLock()
{
	if(m_pThreadMutex)
	{
		m_pThreadMutex->Unlock();
	}
}